package com.me.test.threadpool.xly;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;


public class ThreadPoolManager {

	private static int DEFAULT_POOL_SIZE = 4;
	private List<WorkThread> threadPool;
	private Queue<Task> taskQueue;
	private int poolSize;
	
	public ThreadPoolManager(){
		this(DEFAULT_POOL_SIZE);
	}
	
	public ThreadPoolManager(int poolSize){
		if(poolSize <= 0){
			this.poolSize = DEFAULT_POOL_SIZE;
		}else{
			this.poolSize = poolSize;
		}
		
		threadPool = new ArrayList<WorkThread>(this.poolSize);
		taskQueue = new ConcurrentLinkedQueue<Task>();
		
		startup();
	}
	
	/**
	 * 启动线程池 开始处理任务
	 */
	private void startup(){
		System.out.println("启动工作线程。。。");
		synchronized(taskQueue){
			for(int i = 0; i < DEFAULT_POOL_SIZE; i++){
				WorkThread workThread = new WorkThread(taskQueue);
				workThread.setName("WorkThread-" + i);
				threadPool.add( workThread );
				workThread.start();
			}
		}
		
	}
	
	/**
	 * 停止工作线程。工作线程不一定立即停止，只有在线程处于运行状态时会立即停止
	 */
	public void shutdown(){
		System.out.println("停止工作线程.");
		synchronized(taskQueue){
			for(int i = 0; i < DEFAULT_POOL_SIZE; i++){
				threadPool.get(i).shutdown();
			}
		}
	}
	
	/**
	 * 添加消息到队尾,  
	 */
	public void addTask(Task task){
		synchronized(taskQueue){
			taskQueue.add(task);
			taskQueue.notifyAll();  
		}
	}

}
